/*
 *  Copyright © 2014 CIB Co.Ltd
 *  * All right reserved
 *  * Auther:jin xingwang
 *
 */

package com.wsd.scheduler;

import com.alibaba.fastjson.JSON;
import com.cif.domain.AccountInfo;
import com.cif.service.AccountService;
import com.cif.service.CustomerService;
import com.wsd.common.Result;
import com.wsd.domain.LoanInformation;
import com.wsd.service.ILoanService;
import org.apache.dubbo.config.annotation.Reference;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 自动放款
 * @author 靳兴旺
 * @version 1.0.0 2020-7-21
 */

public class MakeLoansTimer extends QuartzJobBean {

    /**
     * 放款成功
     */
    private final String OK = "1";

    static Logger logger = LoggerFactory.getLogger(MakeLoansTimer.class);

    @Autowired
    private ILoanService loanService;

    @Reference(version = "1.0.0", url = "${dubbo.service.cifurl}")
    private AccountService accountService;

    /**
     * 任务执行
     * @param jobExecutionContext 上下文
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        logger.info("开始执行批量授信任务， 时间{}", LocalDateTime.now());
        List<LoanInformation> loanInformations = loanService.applyingLoanInformation();
        List<AccountInfo> accountInfos = new ArrayList<>();
        for (LoanInformation loanInformation : loanInformations) {
            Integer isSuccess = accountService.loanToAccount(loanInformation.getCustomerId(), loanInformation.getLoanAmount())
                    .getResultCode();
            if (isSuccess != 10001){
                logger.error("用户：{} 放款失败，时间{}", loanInformation.getCustomerId(), LocalDateTime.now());
            }
            loanInformation.setLoanStatus(OK);
        }
        loanService.updateLoanInformationStatus(loanInformations);
        logger.info("批量授信任务执行结束， 时间{}", LocalDateTime.now());
    }
}
